#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: ct_operate_node03.py
@version:
@time: 2022/06/08 
"""
from TapClientCore.T07_CaseTemplate.v2.CT03_task.ct_task import CTTask, allure, logger, time, check_wait


# 左连接
class CTTaskNode03Join(CTTask):
    join = ''
    # 这个左联中需要的字段改名
    name = '自动化-字段改名'
    rename_suffix = ''

    # 节点信息更新
    def join_node_update(self, task_name, task_id):
        # 数据处理节点 field rename 节点更新
        time.sleep(check_wait)
        with allure.step(f'获取node schema 并进行{self.name}节点更新'):
            source_node_id = self.TMF_TASK.query_task_by_id(task_id).get('data').get('dag').get('edges')[0].get(
                'source')
            fields = self.get_field_by_node_id(source_node_id)
            field_update = self.rename_meta(fields)
        with allure.step('field rename 节点更新'):
            field_rename = {
                'operations': field_update
            }
            self.update_task_op_node(task_name, self.name, field_rename)

    # 字段改名修改meta信息修改
    def rename_meta(self, fields):
        return [
            {
                'field': one.get('field_name'),
                'field_name': one.get('field_name') + self.rename_suffix,
                'firstRest': False,
                'id': one.get('id'),
                'label': one.get('field_name') + self.rename_suffix,
                'op': 'RENAME',
                'operand': one.get('field_name') + self.rename_suffix,
                'primary_key_position': one.get('primary_key_position'),
                'reset': False,
                'table_name': 'table',
                'type': one.get('data_type')
            } if one.get('primary_key_position') else
            {
                'field': one.get('field_name'),
                'field_name': one.get('field_name') + self.rename_suffix,
                'firstRest': False,
                'id': one.get('id'),
                'label': one.get('field_name') + self.rename_suffix,
                'op': 'RENAME',
                'operand': one.get('field_name') + self.rename_suffix,
                'reset': False,
                'table_name': 'table',
                'type': one.get('data_type')
            }
            for one in fields
        ]

    # join修改配置信息获取
    def JOIN(self, data):
        node_config = data.pop('node_config')
        self.join = node_config.get('join')
        self.rename_suffix = node_config.get('rename')
        data['task_config']['node'] = node_config
        return data

    @staticmethod
    def join_operate(data):
        tmp = []
        for one in data:
            t = list(one)
            new = []
            for _ in t:
                new.append(_)
                new.append(_)
            tmp.append(tuple(new))
        return tmp

    def join_column_operate(self, data):
        data.extend([f'{i}{self.rename_suffix}' for i in data])
        data.sort()
        return data

    def TASK_LEFT_JOIN_INITIAL(self, parallel_data):
        """
                全量不校验任务运行,并行执行任务
                :param parallel_data:
                :return:
                """
        data = None
        record_id = None
        task_name = None
        # 随机等待
        self.random_wait()
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            operate = data.pop('operate')
            operate_source = operate.get('source')
            source_info = operate_source.get('source_info')
            source_table = operate_source.get('table')
            operate_target = operate.get('target')
            target_info = operate_target.get('target_info')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.JOIN(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table

            source_where_column = operate_source.get('where')
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            # stats check
            _stats = operate.get('stats_check').get('initial')
            _stats_initial = _stats.get('insert')
            self.drop_target_table(_target)
            with allure.step('创建任务'):
                task_id = self.create_data_copy_development(data).get('id')

            self.join_node_update(task_name, task_id)
            # 等待重新推演
            time.sleep(check_wait)

            # initial stats insert 校验
            with allure.step('任务状态等待'):
                self.scheduled_task_wait_it_complete(task_name)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # check
            self.tap_join_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate,
            )
        finally:
            self.release_table(record_id)
            self.generate_task_url(task_name, data.get('task_type'))
            logger.info(self.task_url)
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    def TASK_LEFT_JOIN_CDC(self, parallel_data):
        data = None
        # 随机等待
        self.random_wait()
        record_id = None
        source_delete = None
        task_name = None
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')

            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.JOIN(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            # stats check
            _stats = operate.get('stats_check').get('cdc')
            _stats_initial = _stats.get('initial')
            _stats_insert = _stats.get('insert')
            _stats_update = _stats.get('update')
            _stats_delete = _stats.get('delete')
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                task_id = self.create_data_copy_development(data).get('id')

            self.join_node_update(task_name, task_id)
            # 等待重新推演
            time.sleep(check_wait)

            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 增量任务等待时间
            logger.info('等待一段时间')
            time.sleep(180)
            # insert
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # check
            self.tap_join_node_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )
            # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            self.tap_join_node_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )
            # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # check
            self.tap_join_node_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    def TASK_LEFT_JOIN_INITIAL_CDC(self, parallel_data):
        data = None
        source_delete = None
        record_id = None
        _source = None
        _target = None
        task_name = None
        try:
            # 随机等待
            self.random_wait()
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')
            # connector
            _source = self.init_connector(source_info)
            _target = self.init_connector(target_info)
            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            task_name = data.get('task_config').get('config').get('name')

            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            data = self.JOIN(data)

            # stats check
            _stats = operate.get('stats_check').get('initial+cdc')
            _stats_initial = _stats.get('initial')
            _stats_insert = _stats.get('insert')
            _stats_update = _stats.get('update')
            _stats_delete = _stats.get('delete')
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                task_id = self.create_data_copy_development(data).get('id')

                self.join_node_update(task_name, task_id)
            # 等待重新推演
            time.sleep(check_wait)

            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 全量阶段校验
            logger.info('initial check')
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # check
            self.tap_join_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )
            # 增量阶段校验
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # check
            self.tap_join_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )  # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            self.tap_join_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )  # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # check
            self.tap_join_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.join_operate,
                self.join_column_operate
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass
